#encoding:utf-8

from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename



class FileEditor:
    def __init__(self):
        window = Tk()
        window.title("打开和保存文件")

        menubar = Menu(window)
        window.config(menu = menubar)

        operationMenu = Menu(menubar, tearoff = 0)
        menubar.add_cascade(label = "文件(F)", menu = operationMenu)
        operationMenu.add_command(label = "打开文件(O)", command = self.openfile)
        operationMenu.add_command(label = "保存文件(S)", command = self.savefile)

        frame1 = Frame(window)
        frame1.grid(row = 1, column = 1, sticky = W)


        openImage = PhotoImage(file = "image/open.gif")
        saveImage = PhotoImage(file = "image/save.gif")

        Button(frame1, image = openImage, command = self.openfile).grid(row = 1, column = 1, sticky = W)
        Button(frame1, image = saveImage, command = self.savefile).grid(row = 1, column = 2)

        frame2 = Frame(window)
        frame2.grid(row = 2, column = 1)

        scrollbar = Scrollbar(frame2)
        scrollbar.pack(side = RIGHT, fill = Y)
        self.text = Text(frame2, width = 40, height = 20,
                         wrap = WORD, yscrollcommand = scrollbar.set)
        self.text.pack()
        scrollbar.config(command = self.text.yview())



        window.mainloop()



    def openfile(self):
        openfileforReading = askopenfilename()
        infile = open(openfileforReading, "r")
        self.text.insert(END, infile.read())
        infile.close()

    def savefile(self):
        openfileforWriting = asksaveasfilename()
        outfile = open(openfileforWriting, "w")
        outfile.write(self.text.get(1.0, END))
        outfile.close()


FileEditor()